package com.cs.deviceManager.mqtt.ota.manager;


import com.cs.deviceManager.mqtt.ota.OtaLocalCache;
import com.cs.deviceManager.mqtt.ota.OtaLocalReporter;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author zizige
 * @date 2025年08月25日 14:32
 */

@Component
public class OtaReporterManager {

    private final ConcurrentMap<String, OtaLocalReporter> activeReporters = new ConcurrentHashMap<>();

    public void register(String deviceId, OtaLocalReporter reporter) {
        activeReporters.put(deviceId, reporter);
    }

    public OtaLocalReporter getReporter(String deviceId) {
        return activeReporters.get(deviceId);
    }

    public void remove(String deviceId) {
        activeReporters.remove(deviceId);
    }

    /**
     * 获取设备的完整 OTA 状态：状态 + 实例日志
     */
    public OtaLocalCache.OtaFullStatus getFullStatus(String deviceId, OtaLocalCache otaLocalCache) {
        // 获取最新状态
        OtaLocalCache.OtaStatus status = otaLocalCache.getStatus(deviceId);

        // 获取当前 reporter 的日志（如果存在）
        List<String> logs = Collections.emptyList();
        OtaLocalReporter reporter = getReporter(deviceId);
        if (reporter != null) {
            logs = reporter.getLogs(); // reporter 自带日志
        }

        return new OtaLocalCache.OtaFullStatus(status, logs);
    }
}